package com.gzx.plugin.tjzy.modular.caffeine;

import cn.hutool.json.JSONObject;
import com.github.benmanes.caffeine.cache.Cache;
import lombok.RequiredArgsConstructor;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import vip.xiaonuo.auth.core.util.StpLoginUserUtil;
import vip.xiaonuo.sys.api.SysUserApi;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author zjt
 * @description
 * @date 2025/5/21 14:55
 */
@Component
@RequiredArgsConstructor
public class UserCaffeine {

    private final SysUserApi userApi;

    private final Cache<String, Map<String, JSONObject>> userCache;

    @Scheduled(fixedRate = 60_000)
    public void refreshTransCache() {
        List<JSONObject> userJsonList = userApi.getAllUser();
        for (JSONObject userJson : userJsonList) {
            String tenantId = userJson.getStr("tenantId");
            String account = userJson.getStr("account");
            String userId = userJson.getStr("id");
            // 处理userAccountCache
            Map<String, JSONObject> accountMap = userCache.getIfPresent(tenantId);
            if (accountMap == null) {
                accountMap = new ConcurrentHashMap<>();
            }
            accountMap.put(account, userJson);
            accountMap.put(userId, userJson);
            userCache.put(tenantId, accountMap);
        }
    }

    public Map<String, JSONObject> getUserMapByTenantId(String tenantId) {
        return userCache.getIfPresent(tenantId);
    }

    public Map<String, JSONObject> getUserMap() {
        return userCache.getIfPresent(StpLoginUserUtil.getLoginUser().getTenantId());
    }
}
